# 多阶段构建 - 前端构建阶段
FROM node:20-alpine AS frontend-builder

WORKDIR /app/frontend

# 复制前端依赖文件
COPY frontend/package*.json ./

# 设置npm配置并安装依赖
RUN npm config set registry https://registry.npmmirror.com/ && \
    npm ci --include=dev

# 复制前端源码并构建
COPY frontend/ ./
RUN npm run build:prod && \
    npm cache clean --force

# 主运行阶段
FROM python:3.11-slim

# 安装系统依赖
    RUN echo "deb http://mirrors.aliyun.com/debian/ bullseye main non-free contrib" > /etc/apt/sources.list && \
        echo "deb-src http://mirrors.aliyun.com/debian/ bullseye main non-free contrib" >> /etc/apt/sources.list && \
        echo "deb http://mirrors.aliyun.com/debian-security/ bullseye-security main" >> /etc/apt/sources.list && \
        echo "deb-src http://mirrors.aliyun.com/debian-security/ bullseye-security main" >> /etc/apt/sources.list && \
        echo "deb http://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib" >> /etc/apt/sources.list && \
        echo "deb-src http://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib" >> /etc/apt/sources.list && \
        apt-get update && apt-get install -y \
        supervisor \
        nginx \
        curl \
        gettext-base \
        tzdata \
        && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制后端依赖文件并安装
COPY backend/requirements.txt ./backend/
# RUN pip install --no-cache-dir -r backend/requirements.txt
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r backend/requirements.txt

# 复制后端代码
COPY backend/ ./backend/

# 从前端构建阶段复制构建结果
COPY --from=frontend-builder /app/frontend/dist ./frontend/dist

# 生产环境不需要前端源码和开发依赖

# 创建数据持久化目录
RUN mkdir -p /app/data /app/config /app/logs

# 配置nginx模板
RUN rm /etc/nginx/sites-enabled/default
COPY <<EOF /etc/nginx/sites-available/torrentchecker.template
server {
    listen \${FRONTEND_PORT};
    server_name _;
    
    # 日志配置
    access_log /app/logs/nginx_access.log;
    error_log /app/logs/nginx_error.log;
    
    # 启用gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    # 前端静态文件
    location / {
        root /app/frontend/dist;
        try_files \$uri \$uri/ /index.html;
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }
    
    # API代理到后端
    location /api/ {
        proxy_pass http://127.0.0.1:\${BACKEND_PORT}/api/;
        proxy_set_header Host \$http_host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Forwarded-Host \$http_host;
        proxy_set_header X-Forwarded-Port \$server_port;
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;

    }
}
EOF

RUN ln -s /etc/nginx/sites-available/torrentchecker /etc/nginx/sites-enabled/

# 配置supervisor
COPY <<EOF /etc/supervisor/conf.d/supervisord.conf
[supervisord]
nodaemon=true
user=root
logfile=/app/logs/supervisord.log
pidfile=/var/run/supervisord.pid

[program:backend]
command=python -m uvicorn app.main:app --host 0.0.0.0 --port %(ENV_BACKEND_PORT)s --workers 1 --access-log --log-config /app/backend/logging_config.json
directory=/app/backend
autorestart=true
stdout_logfile=/app/logs/backend.log
stderr_logfile=/app/logs/backend_error.log
environment=PYTHONPATH=/app/backend

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autorestart=true
stdout_logfile=/app/logs/nginx.log
stderr_logfile=/app/logs/nginx_error.log
EOF



# 创建启动脚本
COPY <<EOF /app/start.sh
#!/bin/bash

# 设置时区（支持环境变量TZ）
export TZ=\${TZ:-Asia/Shanghai}
ln -sf /usr/share/zoneinfo/\$TZ /etc/localtime
echo "$TZ" > /etc/timezone

# 设置默认端口
export FRONTEND_PORT=\${FRONTEND_PORT:-9980}
export BACKEND_PORT=\${BACKEND_PORT:-9900}

# 生成nginx配置文件
envsubst '\$FRONTEND_PORT \$BACKEND_PORT' < /etc/nginx/sites-available/torrentchecker.template > /etc/nginx/sites-available/torrentchecker
ln -sf /etc/nginx/sites-available/torrentchecker /etc/nginx/sites-enabled/

# 确保数据目录权限
chown -R root:root /app/data /app/config /app/logs
chmod -R 755 /app/data /app/config /app/logs

# 初始化数据库（如果不存在）
if [ ! -f "/app/data/torrent_checker.db" ]; then
    echo "初始化数据库..."
    cd /app/backend
    python -c "from app.database import engine; from app.models import Base; Base.metadata.create_all(bind=engine)"
fi

# 启动supervisor
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
EOF

RUN chmod +x /app/start.sh

# 设置环境变量
ENV PYTHONPATH=/app/backend
ENV NODE_ENV=production
ENV FRONTEND_PORT=9980
ENV BACKEND_PORT=9900
ENV DATABASE_URL=sqlite:////app/data/torrent_checker.db

# 暴露端口（使用ARG在构建时设置）
ARG FRONTEND_PORT=9980
ARG BACKEND_PORT=9900
EXPOSE $FRONTEND_PORT $BACKEND_PORT

# 数据卷
VOLUME ["/app/data", "/app/config", "/app/logs"]

# 以root用户运行
USER root

# 启动命令
CMD ["/app/start.sh"]